import java.util.Arrays;

public class MyArrayList {
    public int[] elem;
    private static final int DEFAULT_SIZE = 10;
    private  int len = 0;
    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }
    public MyArrayList(int L) {
        this.elem = new int[L];
    }
    //打印链表
    public void display() {
        System.out.print("[");
        for (int i = 0;i < len; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println("]");
        System.out.println();
    }
    //在最后添加一个元素
    public void add(int data) {
        if(isFull()){
            extendArr();
        }
        this.elem[len] = data;
        this.len++;
    }
    //判断链表有没有满
    public boolean isFull() {
        if(this.elem.length == len){
            return true;
        }else{
            return false;
        }
    }
    //判断传入add的位置是否合法
    private boolean checkPosInAdd(int pos) {
        if(pos > len - 1 || pos < 0){
            return false;
        }
        return true;
    }
    // 在 pos 位置新增元素
    public void add(int pos, int data) {
        if(!checkPosInAdd(pos)){
            throw new PosException(pos + "位置不合法 ");
        }
        if(isFull()){
            extendArr();
        }else{
            for (int i = len - 1; i >= pos; i--) {
                this.elem[i + 1] = this.elem[i];
            }
            this.elem[pos] = data;
            this.len++;
        }
    }
    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < len; i++) {
            if(this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < len; i++) {
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    // 获取 pos 位置的元素
    public int get(int pos) {
        return this.elem[pos];
    }
    private boolean isEmpty() {
        return this.len != 0;
    }
    // 给 pos 位置的元素设为【更新为】 value
    public void set(int pos, int value) {
        this.elem[pos] = value;
    }
      //删除第一次出现的关键字key

    public void remove(int key) {
        int pos = indexOf(key);
        for (int i = pos; i < len - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        len--;
    }
    //获取长度
    public int size() {
        return this.len;
    }
    public void clear() {
        for (int i = 0; i < len; i++) {
            this.elem[i] = 0;
        }
        this.len = 0;
    }
    public void extendArr(){
        this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
    }
}
